import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { GetLastURL } from '../../services/last-url.service';

@Component({
  selector: 'm-usb-list',
  templateUrl: './usb-list.component.html',
  styleUrls: ['./usb-list.component.scss'],
})
export class UsbListComponent implements OnInit {
  result$ = this.route.data.pipe(map((data) => data['list']));
  operation: number;
  searchKey: string = '';

  constructor(private route: ActivatedRoute,
    private router: Router
    ) {}

  ngOnInit() {
    this.route.queryParamMap.subscribe(data => {
      this.operation = +(data.get('operation_type') || 0);
      this.searchKey = data.get('keywords') || '';
  })
  }

  onOperation(operation) {
    if (this.operation == operation) {
      return;
    }
    this.operation = operation;
    this.startSearch();
  }

  onSearchKey(key: string, exec: boolean) {
    if (this.searchKey == key) {
      return;
    }
    this.searchKey = key;
    if (!exec) {
      return;
    }
    this.startSearch();
  }

  startSearch() {
    let params = { page: 1 };
    if (this.operation != 0) {
        params['operation_type'] = this.operation;
    }
    if (this.searchKey.length != 0) {
        params['keywords'] = this.searchKey;
    }

    this.router.navigate([this.router.url.split('?')[0]], {
        relativeTo: this.route,
        queryParams: params
    })
}
}
